package com.xiyuan.smartutils.client.http;

import com.xiyuan.smartutils.Files;
import com.xiyuan.smartutils.IoUtils;
import com.xiyuan.smartutils.Validates;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

/**
 * HTTPS文件下载类
 *
 * @version v1.0.0 @author lgz 2017-9-21 新建与整理
 */
public class HttpDownload extends HttpClient {
    private String fileDir;
    private String fileName;
    private File file;
    
    public HttpDownload(String url) {
        super(url, _GET_);
    }
    
    public void setFileDir(String fileDir) {
        this.fileDir = fileDir;
    }
    
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    
    public String getFileDir() {
        return fileDir;
    }
    
    public File getFile() {
        return file;
    }
    
    public String getFileName() {
        return fileName;
    }
    
    @Override
    protected boolean doPreRequestProperty() {
        if (Files.exists(fileDir)) {
            if (!Files.isDirectory(fileDir)) {
                responseStatus = _72_PARAM_NOT_SATISFIED_.getCode();
                responseText = "请求的文件存放目录不正确";
                return false;
            }
        }
        else {
            if (!Files.mkdir(fileDir)) {
                responseStatus = _72_PARAM_NOT_SATISFIED_.getCode();
                responseText = "请求的文件存放目录不正确";
                return false;
            }
        }
        
        //如果没有指定类型，则设置支持全部类型
        if (hasRequestHeader("Accept")) {addRequestProperty("Accept", "*/*");}
        
        return true;
    }
    
    @Override
    protected void doReadContent(HttpURLConnection conn) throws IOException {
        if (responseStatus == _302_FOUND_.getCode()) {
            //重定向
            responseText = conn.getHeaderField("Location");
            return;
        }
        
        if (responseStatus != _200_OK_.getCode()) {
            //错误
            responseText = getResponseError(conn);
            return;
        }
        
        //成功，获取文件名，如果用户未指定文件名则取连接中是否有文件名
        if (Validates.isEmpty(fileName)) {fileName = getFileName(conn);}
        
        if (Validates.isEmpty(fileName)) {
            //如果未指定且连接属性中没有则查看URL中有没有，判断方法是看有没有2-5位后缀
            String fileExt = Files.getFileExt(url);
            if (Validates.isAlphabeticLen(fileExt, 2, 5)) {fileName = Files.getFileName(url, "/");}
        }
        
        if (Validates.isEmpty(fileName)) {
            //未配置、连接属性中没有、URL没有则报错
            responseStatus = _72_PARAM_NOT_SATISFIED_.getCode();
            responseText = "未指定文件名称";
            return;
        }
        
        file = new File(fileDir, fileName);
        
        try (FileOutputStream output = new FileOutputStream(file); InputStream input = conn.getInputStream()) {
            IoUtils.putBytes(input, output);
        }
        
        responseText = "下载成功";
    }
}
